﻿using System;
using System.Web;
using Newtonsoft.Json;
using eCommerce.core.Helpers;
using eCommerce.db.BORespository;
using eCommerce.db.DataRespository;
using eCommerce.log;

namespace eCommerce.db.Action
{
    public class OrderDetailAction : IBaseAction
    {
        public void Do(HttpContext context)
        {
            var actionName = Utils.GetIdFromRequestString(Utils.Action, string.Empty);

            var responseData = new ResponseData();
            switch (actionName)
            {
                case "listbyorder":
                    responseData = GetListByOrder();
                    break;
                
                case "":
                    responseData.Success = false;
                    responseData.Message = "Can not found this action.";
                    break;
            }

            var jSonString = JsonConvert.SerializeObject(responseData, Utils.SerializeFormat("MM/dd/yyyy HH:mm:ss"));
            if (!string.IsNullOrEmpty(context.Request.Params["callback"]))
                jSonString = string.Format("{0}({1})", context.Request.Params["callback"], jSonString);
            context.Response.Write(jSonString);
        }

        private static ResponseData GetListByOrder()
        {
            var responseData = new ResponseData();

            var orderId = Utils.GetIdFromRequestString(Utils.OrderId, 0);

            try
            {
                var lstOrder = OrderDetailBo.GetListByOrderId(orderId);
                for (int i = 0; i < lstOrder.Count; i++)
                {
                    lstOrder[i].ItemIndex       = Utils.CalcItemIndex(i, Constant.PageIndex, lstOrder.Count);
                    lstOrder[i].FormatUnitPrice = Utils.FormatPrice(lstOrder[i].UnitPrice);
                }

                responseData.Success    = true;
                responseData.Data       = lstOrder;
                responseData.TotalRow   = lstOrder.Count;
            }
            catch (Exception ex)
            {
                responseData.Success = false;
                responseData.Message = ex.Message;
                Logger.WriteLog(Logger.LogType.Error, ex.Message);
            }

            return responseData;
        }
    }
}
